package cn.yusei.teamTribe.service.team;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.yusei.teamTribe.constant.PermissionType;
import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.dao.team.TeamDAO;
import cn.yusei.teamTribe.dao.team.TeamInfoDAO;
import cn.yusei.teamTribe.dao.team.po.TeamPO;
import cn.yusei.teamTribe.entity.Team;
import cn.yusei.teamTribe.exception.TeamIdNotFoundException;
import cn.yusei.teamTribe.service.PermissionService;

@Service
public class TeamInfoService {

	@Autowired
	private TeamDAO teamDAO;
	@Autowired
	private TeamInfoDAO teamInfoDAO;
	@Autowired
	private PermissionService permissionService;
	
	public int update(int userId, Team team){
		if(!permissionService.havePermission(userId, team.getId(), PermissionType.UPDATE_TEAM_INFO, 0))
			return ResponseCode.PERMISSION_FORBIDDEN;
		if(teamInfoDAO.selectById(team.getId()) == null){
			return ResponseCode.TEAM_NOT_EXISTS;
		}
		TeamPO teamPO = new TeamPO();
		BeanUtils.copyProperties(team, teamPO);
		if(teamDAO.exists(teamPO)) {
			return ResponseCode.TEAM_NAME_ALREADY_EXISTS;
		}
		teamInfoDAO.updateById(teamPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public Team getById(int id) throws TeamIdNotFoundException
	{
		TeamPO teamPO = teamInfoDAO.selectById(id);
		if(teamPO == null)
			throw new TeamIdNotFoundException("团队 id [" + id + "] 不存在");
		Team team = new Team();
		BeanUtils.copyProperties(teamPO, team);
		return team;
	}
	
}
